<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区 -->
    <el-card>
      <!-- 头部的警告区 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类区 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联 -->
          <el-cascader
            clearable
            expand-trigger="hover"
            v-model="shopTypeCascader"
            :options="shopTypeList"
            :props="props"
            ref="shopTypeRef"
            @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <el-tabs v-model="tabsValue" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="dynamic">

          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="handleAddParamsClick"
          >添加参数</el-button>

          <el-table
            :data="dynamicTableData"
            style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.shopParamsValue"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{item}}
                </el-tag>

                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>

                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>

            <el-table-column type="index"/>
            <el-table-column
              prop="shopParamsName"
              label="参数名称"
              />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="warning"
                  icon="el-icon-deit"
                  size="mini"
                  @click="handleEditClick(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-danger"
                  size="mini"
                  @click="handleDelClick(scope.row.shopParamsId)"
                >删除</el-button>
              </template>

            </el-table-column>

          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="static">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="handleAddParamsClick"
          >添加属性</el-button>

          <el-table
            :data="staticTableData"
            style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.shopParamsValue"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{item}}
                </el-tag>

                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>

                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>

            <el-table-column type="index"/>
            <el-table-column
              prop="shopParamsName"
              label="属性名称"
            />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="warning"
                  icon="el-icon-deit"
                  size="mini"
                  @click="handleEditClick(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-danger"
                  size="mini"
                  @click="handleDelClick(scope.row.shopParamsId)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>


      <!-- 新增分类的Dialog -->
      <el-dialog
        :title="title"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="handleAddDialogClose"
        >

        <el-form
          :model="addFrom"
          :rules="addFormRules" ref="addFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="paramsLabel" prop="shopParamsName">
            <el-input v-model="addFrom.shopParamsName"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确 定</el-button>
        </span>
      </el-dialog>


      <!-- 修改分类参数的Dialog -->
      <el-dialog
        :title="updateTitleText"
        :visible.sync="updateDialogVisible"
        width="30%"
        @close="handleUpdateDialogClose"
      >

        <el-form
          :model="updateFrom"
          :rules="updateFormRules" ref="updateFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="updateLabelText" prop="shopParamsName">
            <el-input v-model="updateFrom.shopParamsName"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleUpdateSubmit">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>

  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      // 商品分类列表
      shopTypeList: [],
      // 商品分类级联值
      shopTypeCascader: [],
      // 配置级联选择框
      props: {
        label: 'shopTypeName',
        value: 'shopTypeId',
        children: 'children',
        // 通过 props.checkStrictly = true 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
        checkStrictly: true
      },
      // 被激活页签的
      tabsValue: 'dynamic',
      // 动态参数表单数据
      dynamicTableData:[],
      // 静态属性表单数据
      staticTableData: [],
      // 新增页面展示与关闭
      addDialogVisible: false,
      // 新增表单
      addFrom: {
        shopParamsName: '',
        shopParamsType: '',
        shopTypeId: ''
      },
      // addForm 验证规则
      addFormRules:{
        shopParamsName:[
          {required: true, message:'必须填写名称', trigger:'blur'}
        ]
      },
      // 新增页面的title
      title: '',
      // 新增页面label
      paramsLabel: '',
      // 修改Dialog
      updateDialogVisible: false,
      // 修改，form
      updateFrom: {
        shopParamsName: '',
        shopParamsType: '',
        shopTypeId: ''
      },
      // 修改，验证规则
      updateFormRules: {
        shopParamsName:[
          {required: true, message:'必须填写名称', trigger:'blur'}
        ]
      }
      // ----- data end -----
    }
  },
  created() {
    this.getShopTypeListpeList();
  },
  methods: {
    // 获取所有的商品分类列表
    async getShopTypeListpeList() {
      const {data: res} = await this.$http({
        url: `/shopType/getShopTypeList/tree`,
        method: `get`,
        params: {'type':3}
      });

      if (!res.status) return this.$message.error(res.message);
      this.shopTypeList = this.getTreeData(res.data.shopTypeMapListTree);
    },
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data){
      for(var i=0;i<data.length;i++){
        if(data[i].children.length<1){
          // children若为空数组，则将children设为undefined
          data[i].children=undefined;
        }else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // 商品分类 级联选择框的改变事件
    handleChange() {
      this.getShopParamsList();
      this.$refs.shopTypeRef.dropDownVisible = false;
    },
    // 级联，插槽点击事件

    // tab 改变事件
    handleTabClick() {
      this.getShopParamsList();
    },
    // 获取商品参数列表
    async getShopParamsList() {
      // 如果shopTypeCascader 数据中 的 length 大于 0， 证明选中的父级分类
      // 反之，就说明没有选中任何父级分类
      if (this.shopTypeCascader.length !== 3) {
        this.shopTypeCascader = [];
        this.dynamicTableData = [];
        this.staticTableData = [];
        return
      }
      const {data:res} = await this.$http({
        url: `/shopParams/getShopParamsList`,
        method: `get`,
        params: {'id': this.shopTypeCascader[2], 'type': this.tabsValue}
      });
      if (!res.status) return this.$message.error(res.message);

      res.data.shopParamsList.forEach(item => {
        item.shopParamsValue = item.shopParamsValue ? item.shopParamsValue.split(' ') : [];
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框中输入的值
        item.inputValue = ''
      })

      if (this.tabsValue === 'dynamic') {
        this.dynamicTableData = res.data.shopParamsList;
      } else {
        this.staticTableData = res.data.shopParamsList;
      }
      this.$message.success(res.message);
    },
    // 监控 动态参数编辑点击事件
    handleEditClick(row) {
      this.updateFrom = row;
      this.updateDialogVisible = true;
    },
    // 监控 动态参数编辑删除事件
    async handleDelClick(id) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }
      const {data: res} = await this.$http({
        url: `/shopParams/delShopParams`,
        method: 'delete',
        params: {'id': id}
      });

      if(!res.status) return this.$message.error(res.message);
      await this.getShopParamsList();
      this.$message.success(res.message);
    },
    // 添加动态参数的打开页面
    handleAddParamsClick () {
      this.title = this.tabsValue === "dynamic" ? '新增动态参数':'新增静态属性';
      this.paramsLabel = this.tabsValue === "dynamic" ? '参数名称':'属性名称';
      this.addDialogVisible = true;
    },
    // 新增提交事件
    handleAddSubmit() {
      this.$refs.addFormRef.validate(async valid => {
        this.addFrom.shopParamsType = this.tabsValue;
        this.addFrom.shopTypeId = this.shopTypeCascader[2];
        if (valid) {
          const {data:res} = await this.$http({
            url: `/shopParams/addShopParams`,
            method: 'post',
            data: this.addFrom
          });
          if (!res.status) return this.$message.error(res.message);
          this.$message.success(res.message);
          await this.getShopParamsList();
          this.addDialogVisible = false;
        }
      });
    },
    // 监听新增分类Dialog的关闭事件
    handleAddDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 修改， 关闭事件
    handleUpdateDialogClose() {
      this.$refs.updateFormRef.resetFields();
    },
    // 修改，提交
    handleUpdateSubmit() {
      this.$refs.updateFormRef.validate(async valid => {
        if (valid) {
          const {data:res} = await this.$http({
            url: `/shopParams/updateShopParams`,
            method: 'put',
            params: this.updateFrom
          });
          if (!res.status) return this.$message.error(res.message);
          this.$message.success(res.message);
          await this.getShopParamsList();
          this.updateDialogVisible = false;
        }
      });
    },
    // 文本框失去焦点或按下enter建都会触发
    handleInputConfirm(row) {
      if(row.inputValue.trim().length === 0) {
        row.inputValue = '';
        row.inputVisible = false;
        return;
      }

      // 如果没有 return ，则证明输入内容需要做后续处理
      row.shopParamsValue.push(row.inputValue.trim());
      row.inputValue = '';
      row.inputVisible = false;
      // 需要存到数据库中
      this.updateShopParamsValue(row);
    },
    // 点击按钮展示文本输入框
    showInput(row) {
      row.inputVisible = true;
      // 让文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除对应的 tag
    handleClose(index, row) {
      row.shopParamsValue.splice(index, 1);
      this.updateShopParamsValue(row);
    },
    // 更新分类参数的 shopParamsValue
    async updateShopParamsValue (row) {
      let putData = {};
      Object.assign(putData, row);
      putData.shopParamsValue = putData.shopParamsValue.join(' ');
      // 需要发起请求保存操作
      const {data:res} = await this.$http({
        url:`/shopParams/updateShopParams`,
        method:'put',
        params: putData
      });
      if (!res.status) return this.$message.error(res.message);
      this.$message.success(res.message);
    }

    // ----- methods end -----
  },
  computed: {
    // 计算tab 是否被禁用，禁用true，否则返回false
    isBtnDisable() {
      if (this.shopTypeCascader.length !== 3) return true;
      return false;
    },
    // 当前选中的三级分类的Id
    cateId() {
      if(this.shopTypeCascader.length === 3) return this.shopTypeCascader[2];
      return null;
    },
    // 修改， 标题
    updateTitleText() {
      return this.tabsValue === "dynamic" ? '修改动态参数':'修改静态属性';
    },
    // 修改，label
    updateLabelText() {
      return this.tabsValue === "dynamic" ? '参数名称':'属性名称';
    }
    // ----- computed end -----
  }

}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag{
  margin-right: 15px;
}
.input-new-tag{
  width: 120px;
}
</style>
